package com.google.code.cisx.client.gadgets.deprecated;

import com.google.code.cisx.client.GoogleFeedRequest;
import com.google.code.cisx.client.GoogleFeedRequestHandler;
import com.google.code.cisx.client.model.Gadget;
import com.google.code.cisx.client.model.GadgetClass;
import com.google.code.cisx.client.model.UserPref;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;

public class NewsGadget extends Gadget implements GoogleFeedRequestHandler {

  public static class Class extends GadgetClass {
    public static UserPref feed = new UserPref("Feed", "http://feeds.feedburner.com/Techcrunch");

    public Class() {
      super("News", true);
      addUserPref(feed);
    }

    public Gadget newGadget() {
      return new NewsGadget(this);
    }
  }

  private VerticalPanel list = new VerticalPanel();

  protected NewsGadget(Class c) {
    super(c);
    initWidget(list);
    setStyleName("News");
  }

  public void refresh() {
    list.clear();
    String url = (String) getUserPrefValue(Class.feed);
    GoogleFeedRequest.get(url, this);
  }

  public void onRequestComplete(String result) {
    JSONObject feed = (JSONObject) JSONParser.parse(result);
    JSONArray entries = (JSONArray) feed.get("entries");
    for (int i = 0; i < entries.size(); i++) {
      JSONObject item = (JSONObject) entries.get(i);
      JSONString title = (JSONString) item.get("title");
      JSONString url = (JSONString) item.get("link");
      HTML html = new HTML("<a href='" + url.stringValue() + "' target='_blank'>"
          + title.stringValue() + "</a>");
      html.setStyleName("News-Item");
      list.add(html);
    }
  }

  public void onRequestFailed(String error) {
    list.add(new HTML(error));
  }
}
